package xcf.data.session.defalut;

import xcf.data.model.Configuration;
import xcf.data.session.IExecutor;
import xcf.data.session.ISqlSession;

import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSession implements ISqlSession {

    private final Configuration configuration;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... paramValues) throws Exception {
        IExecutor executor = new DefaultExecutor();
        return executor.query(configuration, configuration.getMapperStatementMap().get(statementId), paramValues);
    }

    @Override
    public <T> T selectOne(String statementId, Object... paramVales) throws Exception {
        List<Object> objects = selectList(statementId, paramVales);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        } else if (objects.size() > 1) {
            throw new RuntimeException("return result more then one");
        }
        return null;
    }

    @Override
    public <T> T getMapper(Class<T> clazz) {
        Object proxy = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, (proxy1, method, args) -> {
            Class<?> declaringClass = method.getDeclaringClass();
            String nameSpace = declaringClass.getName();
            String name = method.getName();
            String statementId = nameSpace + "." + name;
            // 获取返回值的
            Type genericReturnType = method.getGenericReturnType();
            if (genericReturnType instanceof ParameterizedType) {
                return selectList(statementId, args);
            }
            return selectOne(statementId, args);
        });
        return (T) proxy;
    }
}
